import React, { useState, memo } from 'react';
import './Sidebar.css'; // 引入CSS文件

interface Note {
  id: number;
  title: string;
  body: string;
  updated: string;
  tags: string[]; // 确保这个属性在创建note时始终初始化为[]
}

interface SidebarProps {
  notes: Note[];
  onNoteSelect: (noteId: number) => void;
  onNoteAdd: () => void;
  onNoteDelete: (noteId: number) => void;
  activeNote: Note | null; // 添加 activeNote 属性
  onImport: () => void;
  onExport: () => void;
}

const NoteListItem = memo(({ note, isActive, onSelect, onDelete }: {
  note: Note;
  isActive: boolean;
  onSelect: (id: number) => void;
  onDelete: (id: number) => void;
}) => {
  const [showDelete, setShowDelete] = useState(false);

  return (
    <div
      className={`notes__list-item ${isActive ? 'selected' : ''}`}
      onClick={() => onSelect(note.id)}
      onMouseEnter={() => setShowDelete(true)}
      onMouseLeave={() => setShowDelete(false)}
    >
      <div className="notes__small-title">{note.title}</div>
      <div className="notes__small-body">
        {note.body && note.body.length > 50 ? `${note.body.substring(0, 50)}...` : note.body}
      </div>
      <div className="notes__small-updated">
        最后编辑时间：
        {new Date(note.updated).toLocaleDateString('zh-CN', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit',
          hour: '2-digit',
          minute: '2-digit'
        })}
      </div>
      {showDelete && (
        <button 
          className="notes__delete-button" 
          onClick={(e) => { 
            e.stopPropagation(); 
            onDelete(note.id); 
          }}
        >
          🗑️
        </button>
      )}
    </div>
  );
});

const Sidebar: React.FC<SidebarProps> = ({ 
  notes, 
  onNoteSelect, 
  onNoteAdd, 
  onNoteDelete, 
  activeNote,
  onImport,
  onExport 
}) => {
  return (
    <div className="notes__sidebar">
      <button className="notes__add" type="button" onClick={onNoteAdd}>
        添加笔记 📒
      </button>
      <div className="notes__controls">
        <button className="notes__control-btn" onClick={onImport}>
          导入笔记 📥
        </button>
        <button className="notes__control-btn" onClick={onExport}>
          导出笔记 📤
        </button>
      </div>
      <div className="notes__list">
        {notes.map((note) => (
          <NoteListItem
            key={note.id}
            note={note}
            isActive={note.id === activeNote?.id}
            onSelect={onNoteSelect}
            onDelete={onNoteDelete}
          />
        ))}
      </div>
    </div>
  );
};

export default memo(Sidebar);
